package com.zyf.service.web;

import cn.hutool.core.codec.Base62;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import com.zyf.service.convert.M3u8ConvertorTemplate;
import com.zyf.service.dao.IVideoService;
import com.zyf.service.entity.VideoEntity;
import com.zyf.service.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

/**
 * @author : xuansy
 * @version : 1.0
 * @date : 2021/5/21 22:45
 * @project_name: ffmpeg-demo
 * @package_name : com.example.ffmpeg.demo.controller
 * @name: TestController
 * @email: 1292798418@qq.com
 * @description :
 */
@RestController
@Slf4j
public class TestController {

    /**
     * 目录路径,这个路径需要包含test.info文件，test.key文件和test.mp4文件
     */
    @Value("${videoPath}")
    private String PATH;

    @Autowired
    private M3u8ConvertorTemplate m3u8ConvertorTemplate;

    @Autowired
    private IVideoService videoServiceImpl;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostMapping("uploadToM3u8")
    public void uploadToM3u8() throws Exception {
        FileInputStream inputStream = new FileInputStream(PATH + "test.mp4");
        String m3u8Url = "http://localhost:8080/upload/test.m3u8";
        String infoUrl = "http://localhost:8080/preview/test.info";
        FFmpegProcessor.convertMediaToM3u8ByHttp(inputStream, m3u8Url, infoUrl);
    }

    @PostMapping("upload/{fileName}")
    public void upload(HttpServletRequest request, @PathVariable("fileName") String fileName) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        FileWriter writer = new FileWriter(PATH + fileName);
        writer.writeFromStream(inputStream);
        IoUtil.close(inputStream);
    }

    /**
     * 预览加密文件
     */
    @GetMapping("preview/{fileName}")
    public void preview(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        FileReader fileReader = new FileReader(PATH + "/" + fileName);
        fileReader.writeToStream(response.getOutputStream());
    }

    /**
     * 预览加密文件
     */
    @GetMapping("viewTs/{fileName}")
    public void viewFile(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        if (!fileName.endsWith(".ts")) {
            VideoEntity video = videoServiceImpl.findFileByName(fileName);
            if (video == null) {
                video = new VideoEntity();
                video.setId(new Random().nextLong());
                video.setFileName(fileName);
                video.setPath(PATH + "/" + fileName);
                fileName = m3u8ConvertorTemplate.verifyAndConvert(PATH + "\\" + fileName);
                video.setTsPath(fileName);
                video.setCreateTime(new Date().toLocaleString());
                video.setUpdateTime(new Date().toLocaleString());
                videoServiceImpl.save(video);
            } else {
                fileName = video.getTsFileName();
            }
        } else {
            fileName = PATH + "\\" + "\\20231010\\22\\25\\" + fileName;
        }
        FileReader fileReader = new FileReader(fileName);
        fileReader.writeToStream(response.getOutputStream());
        //return path;
    }

    /**
     * 预览加密文件
     */
    @GetMapping("view/{fileName}")
    public String viewFileUrl(@PathVariable("fileName") String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ipAddress = IpUtil.getIpAddr(request);
        log.warn("========================>>>>>访问者ip:{}",ipAddress);
        if (!fileName.endsWith(".ts")) {
            VideoEntity video = videoServiceImpl.findFileByName(fileName);
            if (video == null) {
                video = new VideoEntity();
                video.setId(new Random().nextLong());
                video.setFileName(fileName);
                video.setPath(PATH + "/" + fileName);
                fileName = m3u8ConvertorTemplate.verifyAndConvert(PATH + "\\" + fileName);
                video.setTsPath(fileName);
                video.setCreateTime(new Date().toLocaleString());
                video.setUpdateTime(new Date().toLocaleString());
                videoServiceImpl.save(video);
            } else {
                fileName = video.getTsPath();
            }
        } else {
            fileName = PATH + "\\" + "\\20231010\\22\\25\\" + fileName;
        }
//        FileReader fileReader = new FileReader(fileName);
//        fileReader.writeToStream(response.getOutputStream());
        return fileName.replace("C:/Users/Administrator/Downloads/Telegram Desktop","");
    }

    /**
     * 预览加密文件
     */
    @GetMapping("getViewTs1/{path}")
    public void viewFileData(@PathVariable("path") String path, HttpServletResponse response) throws IOException {
        path = Base64.decodeStr(path);
//        if (!fileName.endsWith(".ts")) {
//            VideoEntity video = videoServiceImpl.findFileByName(fileName);
//            if (video == null) {
//                video = new VideoEntity();
//                video.setId(new Random().nextLong());
//                video.setFileName(fileName);
//                video.setPath(PATH + "/" + fileName);
//                fileName = m3u8ConvertorTemplate.verifyAndConvert(PATH + "\\" + fileName);
//                video.setTsPath(fileName);
//                video.setCreateTime(new Date().toLocaleString());
//                video.setUpdateTime( new Date().toLocaleString());
//                videoServiceImpl.save(video);
//            } else {
//                fileName = video.getTsFileName();
//            }
//        } else {
//            fileName = PATH + "\\" + "\\20231010\\22\\25\\" + fileName;
//        }
        FileReader fileReader = new FileReader(path);
        fileReader.writeToStream(response.getOutputStream());
        //return path;
    }


    /**
     * 预览加密文件
     */
    @GetMapping("download/{fileName}")
    public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        FileReader fileReader = new FileReader(PATH + fileName);
        fileReader.writeToStream(response.getOutputStream());
    }

}